/**
 * Copyright 2014 the original author or authors. All rights reserved.
 */
package com.visionet.security.realm;

import javax.annotation.Resource;

import com.visionet.security.domain.dto.UserDTO;
import com.visionet.security.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.visionet.security.domain.entity.User;
import com.visionet.security.support.AuthorizationConverter;

/**
 * 自定义 Stateless Realm
 *
 * @author suxiaojing
 * @date
 * @since 0.0.1
 */
public class StatelessRealm extends AuthorizingRealm {
	@Resource
	private UserService userService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
	 * .shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserDTO securityUser = (UserDTO) principals.getPrimaryPrincipal();
		User user = userService.findOne(securityUser.getId());
		return AuthorizationConverter.getAuthorizationInfo(user);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org
	 * .apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		StatelessToken statelessToken = (StatelessToken) token;
		UserDTO securityUser = new UserDTO();
		securityUser.setLoginName(statelessToken.getLoginName());
		securityUser.setName(statelessToken.getUserName());
		securityUser.setId(statelessToken.getUserId());
		return new SimpleAuthenticationInfo(securityUser, statelessToken.getKey(), getName());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthenticatingRealm#supports(org.apache.shiro.
	 * authc.AuthenticationToken)
	 */
	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof StatelessToken;
	}

}
